﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.SharePoint.Common.Configuration;
using Microsoft.SharePoint;

namespace SharePoint.Contrib.ApplicationSettings
{
    internal class SPSiteSettingsCollection : SettingsCollection
    {
        protected SPWeb site;

        public SPSiteSettingsCollection(IPropertyBag properties, SPWeb site)
            :base(properties)
        {
            this.site = site;
        }

        protected override IEnumerable<Setting> FindAll()
        {
            return (from setting in SPG.RemoveNamespaceFromKeys(FindAllProperties())
                    select new Setting
                    {
                        Id = setting.Key,
                        Value = setting.Value
                    })
                   .ToArray();
        }
        
        protected virtual Dictionary<string, string> FindAllProperties()
        {
            return (from DictionaryEntry property in site.AllProperties
                    where property.Key.ToString().StartsWith(SPG.PNPNamespacePrefix)
                    select property)
                        .ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value.ToString());
        }
    }
}
